package com.addict.applocker.activity;

import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.addict.applocker.Data.AppListItem;
import com.addict.applocker.R;
import com.addict.applocker.adapter.AppListAdapter;
import com.addict.applocker.manager.IceFileDataManager;
import com.addict.applocker.manager.SettingManager;
import com.addict.applocker.util.FreezeUtil;
import com.addict.applocker.view.FloatButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {
    private Toolbar mcToolbar = null;
    private ListView mcListApp = null;
    private FloatButton mcFloatBtn = null;
    private TextView mcTextLoad = null;

    private boolean isAdd = false;
    private AppListAdapter mIceAppAdapter = null;

    private FreezeUtil freezeUtil = null;

    private ProgressDialog mDialog = null;
    private boolean mIsIceAllRun = false;

    // 消息处理块
    public final static int ON_READDATA_END = 0; //读取本地储存的AppData结束
    public final static int ON_ICE_ALLAPP_END = 1; //冻结所有APP线程结束
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case ON_READDATA_END:
                    mIceAppAdapter = new AppListAdapter(MainActivity.this, IceFileDataManager.getData());
                    mcListApp.setAdapter(mIceAppAdapter);
                    break;
                case ON_ICE_ALLAPP_END:
                    if(mDialog == null) return ;
                    mIceAppAdapter = new AppListAdapter(MainActivity.this, IceFileDataManager.getData());
                    mcListApp.setAdapter(mIceAppAdapter);
                    mIsIceAllRun = false;
                    mDialog.hide();
                    Toast.makeText(getApplicationContext(),
                            "软件冻结完毕...", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAppNameOnNormal = getResources().getString(R.string.app_name);
        mAppNameOnAdd = getResources().getString(R.string.app_add);
        mcToolbar = (Toolbar) findViewById(R.id.toolbar);
        mcListApp = (ListView) findViewById(R.id.list_app);
        mcFloatBtn = (FloatButton) findViewById(R.id.float_btn);
        mcTextLoad = (TextView) findViewById(R.id.list_load);

        // ListView 无数据显示TextView
        mcListApp.setEmptyView(findViewById(R.id.list_empty));

        mcToolbar.inflateMenu(R.menu.menu_main);
        mcToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId())
                {
                    case R.id.action_add:
                        if(!isAdd) {
                            goAdd();
                        }
                        break;
                    case R.id.action_setting:
                        startActivity(new Intent(MainActivity.this, SettingActivity.class));
                        break;
                }
                return true;
            }
        });

        mcFloatBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isAdd) {
                    addApp();
                }else {
                    iceAllApp();
                }
            }
        });

        mcListApp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AppListAdapter adapter = (AppListAdapter) mcListApp.getAdapter();

                adapter.setItemStart(position, !adapter.getItem(position).isStart());
                if(!isAdd) { //冻结或解冻程序
                    // 同步保存的应用程序列表
                    AppListItem item = adapter.getItem(position);
                    ArrayList<AppListItem> array = IceFileDataManager.getData();
                    array.get(position).setStart(item.isStart());

                    //为真启用， 为假禁用
                    if(item.isStart()) {
                        freezeUtil.enableApp(item.getAppPackageName());
                    }else {
                        freezeUtil.disableApp(item.getAppPackageName());
                    }
                }
            }
        });

        try {
            freezeUtil = FreezeUtil.getInstance();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "软件获取Root失败！软件失效！",Toast.LENGTH_LONG).show();
            finish();
        }

        // 读取本地储存的那些App数据
        IceFileDataManager.read(getApplicationContext(), mHandler);
    }

    private void addApp() {
        mcListApp.setVisibility(View.INVISIBLE);
        mcTextLoad.setVisibility(View.VISIBLE);

        ArrayList<AppListItem> iceAppArray = IceFileDataManager.getData();
        for(int i = 0; i < mcListApp.getAdapter().getCount(); i++) {
            AppListItem appListItem = (AppListItem) mcListApp.getAdapter().getItem(i);
            boolean isHave = false;
            for(int j = 0; j < iceAppArray.size(); j++) {
                if(appListItem.getAppPackageName().equals(iceAppArray.get(j).getAppPackageName())) {
                    isHave = true;
                    // 取消添加
                    if(!appListItem.isStart()) {
                        // 解除冻结！
                        freezeUtil.enableApp(iceAppArray.get(j).getAppPackageName());

                        iceAppArray.remove(j);
                    }
                    break;
                }
            }

            // 添加！
            if(!isHave && appListItem.isStart()) {
                appListItem.setStart(true);
                iceAppArray.add(appListItem);
            }
        }

        mIceAppAdapter = new AppListAdapter(this, iceAppArray);
        mcListApp.setAdapter(mIceAppAdapter);

        mcTextLoad.setVisibility(View.GONE);
        mcListApp.setVisibility(View.VISIBLE);

        goNormal();
        // 异步保存一下应用程序列表
        IceFileDataManager.save(getApplicationContext());
    }

    private void iceAllApp() {
        if(mIsIceAllRun) return ;

        if(mDialog == null) {
            mDialog = new ProgressDialog(this);
            mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mDialog.setTitle("");
            mDialog.setMessage("处理中...");
            mDialog.setCancelable(false); //对话框不响应back键
            mDialog.setCanceledOnTouchOutside(false); //点击对话框区域外不关闭对话框
        }
        mIsIceAllRun = true;
        mDialog.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // getData保证了save read操作绝对结束
                // mIsIceAllRun保证此线程只有一个， 放心用
                ArrayList<AppListItem> array = IceFileDataManager.getData();
                for(int i = 0; i < array.size(); i++) {
                    AppListItem item = array.get(i);
                    if(item.isStart()) {
                        freezeUtil.disableApp(item.getAppPackageName());
                        item.setStart(false);
                    }
                }
                mHandler.sendEmptyMessage(ON_ICE_ALLAPP_END);
            }
        }).start();
    }

    private void initAddList() {
        mcListApp.setVisibility(View.INVISIBLE);
        mcTextLoad.setVisibility(View.VISIBLE);

        // 获取安装的应用数据
        final ArrayList<AppListItem> iceAppArray = IceFileDataManager.getData(); //不许修改！
        PackageManager pm = getPackageManager();
        List<PackageInfo> installAppArray = pm.getInstalledPackages(0);
        ArrayList<AppListItem> installNewArray = new ArrayList<AppListItem>();

        for(int i = 0; i < installAppArray.size(); i++) {
            PackageInfo info = installAppArray.get(i);
            if((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                //系统应用不给冻结！
                continue;
            }
            boolean isSelect = false;
            for(int j = 0; j < iceAppArray.size(); j++) {
                if(iceAppArray.get(j).getAppPackageName().equals(info.packageName)) {
                    isSelect = true;
                    break;
                }
            }

            String name = info.applicationInfo.loadLabel(pm).toString();
            Drawable drawable = info.applicationInfo.loadIcon(pm);
            AppListItem item = new AppListItem(name, info.packageName, drawable, isSelect);
            installNewArray.add(item);
        }

        mcListApp.setAdapter(new AppListAdapter(this, installNewArray));

        mcTextLoad.setVisibility(View.GONE);
        mcListApp.setVisibility(View.VISIBLE);
    }

    /**
     * 切换状态
     */
    private String mAppNameOnNormal = null;
    private String mAppNameOnAdd = null;
    private void goAdd() {
        isAdd = true;
        mcToolbar.setTitle(mAppNameOnAdd);
        ObjectAnimator animator = ObjectAnimator.ofFloat(mcFloatBtn, "Rotation", 0f, 405f);
        animator.setDuration(500);
        animator.start();
        initAddList();
    }
    private void goNormal() {
        isAdd = false;
        mcToolbar.setTitle(mAppNameOnNormal);
        ObjectAnimator animator = ObjectAnimator.ofFloat(mcFloatBtn, "Rotation", 405f, 0f);
        animator.setDuration(500);
        animator.start();
        mcListApp.setAdapter(mIceAppAdapter);
    }

    @Override
    public void onBackPressed() {
        if(isAdd) {
            goNormal();
        }else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        int useColor = SettingManager.getInstance().getThemeColor();

        mcToolbar.setBackgroundColor(useColor);
        mcFloatBtn.setBackgroundColor(useColor);
    }

    @Override
    protected void onDestroy() {
        SettingManager.getInstance().write(); // 保存设置数据
        IceFileDataManager.save(getApplicationContext());
        try {
            FreezeUtil.getInstance().onDestroy(); // 销毁一下输出
        } catch (Exception e) { }
        super.onDestroy();
    }
}
